"""
日志配置模块 - 提供日志设置
"""

import os
import logging
import logging.handlers
from datetime import datetime

def setup_logging(log_level: str = "INFO", log_dir: str = None) -> None:
    """
    设置日志
    
    参数:
        log_level: 日志级别，可选值：DEBUG, INFO, WARNING, ERROR, CRITICAL
        log_dir: 日志目录，默认为~/.fdas/logs
    """
    # 设置日志级别
    level = getattr(logging, log_level.upper(), logging.INFO)
    
    # 设置日志目录
    if log_dir is None:
        # 获取当前脚本的绝对路径
        current_script_path = os.path.abspath(__file__)
        #获取当前脚本所在的目录
        project_root = os.path.dirname(current_script_path)
        #home_dir = os.path.expanduser("~")
        log_dir = os.path.join(project_root, ".fdas", "logs")
    
    # 创建日志目录
    os.makedirs(log_dir, exist_ok=True)
    
    # 设置日志文件名
    log_file = os.path.join(log_dir, f"fdas_{datetime.now().strftime('%Y%m%d')}.log")
    
    # 设置日志格式
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    
    # 设置控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)
    console_handler.setFormatter(formatter)
    
    # 设置文件处理器
    file_handler = logging.handlers.RotatingFileHandler(
        log_file,
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding="utf-8"
    )
    file_handler.setLevel(level)
    file_handler.setFormatter(formatter)
    
    # 设置根日志器
    root_logger = logging.getLogger()
    root_logger.setLevel(level)
    
    # 清除现有处理器
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 添加处理器
    root_logger.addHandler(console_handler)
    root_logger.addHandler(file_handler)
    
    # 设置第三方库的日志级别
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("matplotlib").setLevel(logging.WARNING)
    logging.getLogger("streamlit").setLevel(logging.WARNING)
    
    # 记录日志设置
    root_logger.info(f"日志级别: {log_level}")
    root_logger.info(f"日志文件: {log_file}")